package com.notary.schedule;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.notary.data.request.SyncDataRequest;
import com.notary.data.service.OfficeRequestService;
import com.notary.util.DesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class SyncDataTask {

    @Value("${office.deskey}")
    private String deskey;

    @Value("${office.code}")
    private String code;

    @Value("${office.syncDataUrl}")
    private String syncDataUrl;

    @Autowired
    private OfficeRequestService officeRequestService;

    private static final Integer MAX_LIMIT = 200;

    /**
     * 定时同步相关数据信息
     * 此方法用于公证处使用其它三方办证系统办证后，数据传输到盈诺签数据中心后，此办证系统主动向数据中心发起请求同步
     * 公证处无第三方办证系统，且盈诺签没有对接到数据中心的，不建议启用此方法
     *
     * @throws Exception
     */
    //每分钟执行一次
    //@Scheduled(cron = "0 */1 * * * ?")
    //每小时执行一次
//    @Scheduled(cron = "0 0 */1 * * ?")
    //设置每15分钟执行一次
//    @Scheduled(cron = "0 */15 * * * ?")
    public void syncData() throws Exception {

        if (syncDataUrl != null) {

            //String today = "2022-08-22";
            //String tomorrow = "2022-08-23";

            //获取今天的日期
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            String today = sf.format(new Date());
            //获取明天的日期
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE, 1);
            String tomorrow = sf.format(calendar.getTime());


            //组装请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("officeNo", code);
            params.put("beginDate", today);
            params.put("endDate", tomorrow);
            params.put("limit", MAX_LIMIT);
            log.info("同步数据请求加密前传参为:{}", params);
            String timestamp = String.valueOf(System.currentTimeMillis() / 100000);
            //获取加密后的参数
            String data = DesUtil.encode(deskey, timestamp, JSONObject.toJSONString(params));
            JSONObject body = new JSONObject();
            body.put("token", deskey);
            body.put("data", data);
            body.put("timestamp", timestamp);
            log.info("同步数据请求加密后传参为:{}", body);
            log.info("同步数据请求地址为:{}", syncDataUrl);
            try {
                String result = HttpUtil.createPost(syncDataUrl)
                        .body(body.toJSONString(), "application/json;utf-8").timeout(8000).execute().body();
                log.info("同步数据请求结果为:{}", result);


                JSONObject json = JSONObject.parseObject(result);

                //0 成功
                if (json.getString("code").equals("0")) {
                    log.info("获取数据同步信息接口成功:{}", json.toJSONString());
                    JSONObject resultObj = json.getJSONObject("data");
                    String resultStr = DesUtil.decode(deskey, resultObj.getString("timestamp"), resultObj.getString("data"));
                    List<SyncDataRequest> syncDataList = JSONArray.parseArray(resultStr, SyncDataRequest.class);
                    if (CollectionUtil.isNotEmpty(syncDataList)) {
                        log.info("解密结果集为:{}", syncDataList);
                        //批量处理解密后的数据
                        officeRequestService.dealSyncData(syncDataList);
                    }
                } else {
                    log.info("获取数据同步信息接口异常:{}", json.toJSONString());
                }
            } catch (Exception ignore) {
                log.info("同步数据一次:{}", ignore.getMessage());
            }
        }else{
            log.info("系统没有配置盈诺签的同步地址，暂时无法同步第三方办证数据");
        }
    }
}
